#include "tools.h"
#include "config.h"

//设置为开机启动
void Tools::AutoRunWithSystem(bool IsAutoRun, QString AppName)
{
    QString AppPath = QApplication::applicationFilePath();
    AppPath = AppPath.replace("/","\\");

    QSettings *reg=new QSettings(
                "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                QSettings::NativeFormat);

    if (IsAutoRun)
    {
        reg->setValue(AppName,AppPath);
    }else
    {
        reg->setValue(AppName,"");
    }
}

//设置编码为UTF8
void Tools::SetUTF8Code()
{
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
    QTextCodec *codec=QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(codec);
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
#endif
}

//窗体居中，并且只有关闭按钮，不能调整大小
void Tools::FormOnlyCloseInCenter(QWidget *frm)
{
    //设置窗体居中
    QDesktopWidget desktop;
    int screenX=desktop.availableGeometry().width();
    int screenY=desktop.availableGeometry().height()-40;
    int frmX=frm->width();
    int frmY=frm->height();
    QPoint movePoint(screenX/2-frmX/2,screenY/2-frmY/2);
    frm->move(movePoint);

    //设置窗体不能调整大小
    frm->setFixedSize(frmX,frmY);

    //设置窗体只有最小化按钮
    frm->setWindowFlags(Qt::WindowCloseButtonHint);
}

//窗体居中显示
void Tools::FormInCenter(QWidget *frm)
{
    int screenX = qApp->desktop()->availableGeometry().width();
    int screenY = qApp->desktop()->availableGeometry().height()-60;
    int wndX = frm->width();
    int wndY = frm->height();
    QPoint movePoint((screenX-wndX)/2,(screenY-wndY)/2);
    frm->move(movePoint);
}

//窗体没有最大化按钮
void Tools::FormNoMaxButton(QWidget *frm)
{
    frm->setWindowFlags(Qt::WindowMinimizeButtonHint);
}

//窗体只有关闭按钮
void Tools::FormOnlyCloseButton(QWidget *frm)
{
    frm->setWindowFlags(Qt::WindowCloseButtonHint);
}

//窗体不能改变大小
void Tools::FormNotResize(QWidget *frm)
{
    frm->setFixedSize(frm->width(),frm->height());
}

// 设置样式
void Tools::setStyle(const QString &style) {
    QFile file(":/qss/resource/qss/" + style + ".css");
    file.open(QIODevice::ReadOnly);
    qApp->setStyleSheet(file.readAll());
    file.close();
}


//延时
void Tools::Sleep(int sec)
{
    QTime dieTime = QTime::currentTime().addMSecs(sec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

//判断是否是IP地址
bool Tools::IsIP(QString IP)
{
    QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    return RegExp.exactMatch(IP);
}


// 获取本机ip地址
QString Tools::GetIP()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
        // 我们使用IPv4地址
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
            return address.toString();
    }
    return "";
}
// 获取文件的大小
QString Tools::GetFileSize(const QString &name) {
    QFileInfo fileInfo(Config::m_strRecvPath + name);
    return CalcSize(fileInfo.size());
}

//获取选择的文件
QString Tools::GetFileName(QString filter)
{
    return QFileDialog::getOpenFileName(NULL,"选择文件",QCoreApplication::applicationDirPath(),filter);
}

//获取选择的文件集合
QStringList Tools::GetFileNames(QString filter)
{
    return QFileDialog::getOpenFileNames(NULL,"选择文件",QCoreApplication::applicationDirPath(),filter);
}

//获取选择的目录
QString Tools::GetFolderName()
{
    return QFileDialog::getExistingDirectory();;
}

//获取文件名，含拓展名
QString Tools::GetFileNameWithExtension(QString strFilePath)
{
    QFileInfo fileInfo(strFilePath);
    return fileInfo.fileName();
}

//获取选择文件夹中的文件
QStringList Tools::GetFolderFileNames(QStringList filter)
{
    QStringList fileList;
    QString strFolder = QFileDialog::getExistingDirectory();
    if (!strFolder.length() == 0)
    {
        QDir myFolder(strFolder);

        if (myFolder.exists())
        {
            fileList = myFolder.entryList(filter);
        }
    }
    return fileList;
}

//文件夹是否存在
bool Tools::FolderIsExist(QString strFolder)
{
    QDir tempFolder(strFolder);
    return tempFolder.exists();
}

//文件是否存在
bool Tools::FileIsExist(QString strFile)
{
    QFile tempFile(strFile);
    return tempFile.exists();
}

// 删除目录下的所有文件，包括子目录
void Tools::CleanDirPath(QString strPath) {
    QDir dir(strPath);
    foreach (QFileInfo mfi ,dir.entryInfoList())
    {
        if (mfi.isFile())
        {
            if (mfi.fileName().endsWith("wav")) {
                bool bOk = QFile::remove(mfi.filePath());
                qDebug() << "Remove Old record files:" << bOk << mfi.filePath();
            }
        }
        else
        {
            if(mfi.fileName()=="." || mfi.fileName() == "..") continue;
            CleanDirPath(mfi.absoluteFilePath());
        }
    }
}

// 复制文件
bool Tools::CopyFile(QString sourceFile, QString targetFile)
{
    if (FileIsExist(targetFile))
    {
        int ret = QMessageBox::information(NULL,"提示","文件已经存在，是否替换？",QMessageBox::Yes | QMessageBox::No);
        if (ret != QMessageBox::Yes)
        {
            return false;
        }
    }
    return QFile::copy(sourceFile,targetFile);
}

// 转换html
void Tools::stringToHtmlFilter(QString &str)
{
    //注意这几行代码的顺序不能乱，否则会造成多次替换
    str.replace("&", "&amp;");
    str.replace(">", "&gt;");
    str.replace("<", "&lt;");
    str.replace("\"", "&quot;");
    str.replace("\'", "&#39;");
    str.replace(" ", "&nbsp;");
    str.replace("\n", "<br>");
    str.replace("\r", "<br>");
}

// string 转换成html
void Tools::stringToHtml(QString &str,QColor crl)
{
    QByteArray array;
    array.append(crl.red());
    array.append(crl.green());
    array.append(crl.blue());
    QString strC(array.toHex());
    str = QString("<span style=\" color:#%1;\">%2</span>").arg(strC).arg(str);
}

// 添加图片
void Tools::imgPathToHtml(QString &path)
{
    path = QString("<img src=\"%1\"/>").arg(path);
}

// 添加文本
void Tools::stringToText(QString &str)
{
    str = QString("<span><p>  %1</span></p>").arg(str);
}


QPixmap Tools::PixmapToRound(const QPixmap &src, int radius)
{
    if (src.isNull()) {
        return QPixmap();
    }

    QSize size(2 * radius, 2 * radius);
    QBitmap mask(size);
    QPainter painter(&mask);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
    painter.setBrush(QColor(0, 0, 0));
    painter.drawRoundedRect(0, 0, size.width(), size.height(), 99, 99);

    QPixmap image = src.scaled(size);
    image.setMask(mask);
    return image;
}

// 灰度
QPixmap Tools::ChangeGrayPixmap(const QImage &image)
{
    QImage newImage = image;
    if (newImage.isNull())
    {
        return QPixmap();
    }

    QColor oldColor;

    for(int x = 0; x < newImage.width(); x++){
        for(int y = 0; y < newImage.height(); y++){
            oldColor = QColor(newImage.pixel(x,y));
            int average = (oldColor.red() + oldColor.green() + oldColor.blue()) / 3;
            newImage.setPixel(x, y, qRgb(average, average, average));
        }
    }

    return QPixmap::fromImage(newImage);
}


// 文件大小转换
QString Tools::CalcSize(qint64 bytes)
{
    QString strUnit;
    double dSize = bytes * 1.0;
    if (dSize <= 0)
    {
        dSize = 0.0;
    }
    else if (dSize < 1024)
    {
        strUnit = "Bytes";
    }
    else if (dSize < 1024 * 1024)
    {
        dSize /= 1024;
        strUnit = "KB";
    }
    else if (dSize < 1024 * 1024 * 1024)
    {
        dSize /= (1024 * 1024);
        strUnit = "MB";
    }
    else
    {
        dSize /= (1024 * 1024 * 1024);
        strUnit = "GB";
    }

    return QString("%1 %2").arg(QString::number(dSize, 'f', 2)).arg(strUnit);
}

// 计算下载速率
QString Tools::CalcSpeed(double speed)
{
    QString strUnit;
    if (speed <= 0)
    {
        speed = 0;
        strUnit = "Bytes/S";
    }
    else if (speed < 1024)
    {
        strUnit = "Bytes/S";
    }
    else if (speed < 1024 * 1024)
    {
        speed /= 1024;
        strUnit = "KB/S";
    }
    else if (speed < 1024 * 1024 * 1024)
    {
        speed /= (1024 * 1024);
        strUnit = "MB/S";
    }
    else
    {
        speed /= (1024 * 1024 * 1024);
        strUnit = "GB/S";
    }

    QString strSpeed = QString::number(speed, 'f', 2);
    return QString("%1 %2").arg(strSpeed).arg(strUnit);
}
